import { Application, FrontendSession } from 'pinus';
import { logger } from '../../../util/Logger';
import { dispatch } from '../../../util/dispatcher';
// var rpc_logger = require('pomelo-logger').getLogger('rpc-log', __filename);

export default function (app: Application) {
    return new Handler(app);
}

export class Handler {
    constructor(private app: Application) {

    }

    /** 当客户端连接时，返回一个可用的connector服务器地址
     * @param  {Object}   msg     客户端请求信息，需要包含uid字段
     * @param  {Object}   session 当前客户端session对象
     */
    async entry(msg: { uid: string }, session: FrontendSession) {
        logger.info("当前服务器ID：",this.app.get("serverId"));
        let uid = msg.uid;
        if (!uid) {
            return {
                code: 500,
                msg: "用户uid字段不能为空"
            }
        }

        //获取所有 connector服务器
        let connectors = this.app.getServersByType("connector");
        if (!connectors || connectors.length === 0) {
            return {
                code: 500,
                msg: "当前没有可用的connector服务器"
            }
        }

        //通过算法，获取到 空闲的 connector服务器
        let con = dispatch(uid, connectors);
        return {
            code: 200,
            host:con.host,
            port:con.clientPort
        };
    }

}